package com.runfast.waimai.task.async;

import cn.jpush.api.push.PushResult;
import com.runfast.common.dao.model.*;
import com.runfast.common.service.RunfastAgentbusinessService;
import com.runfast.common.service.RunfastCuserService;
import com.runfast.common.service.RunfastLoginRecordService;
import com.runfast.common.service.RunfastShopperService;
import com.runfast.common.utils.JsonUtils;
import com.runfast.paotui.dao.model.Role;
import com.runfast.paotui.mq.AmqpClient;
import com.runfast.paotui.utils.JiGuangPushUtil;
import com.runfast.waimai.dao.model.RunfastBusinessAccounts;
import com.runfast.waimai.dao.model.RunfastBusinessAccountsExample;
import com.runfast.waimai.dao.model.RunfastGoodsSellRecord;
import com.runfast.waimai.service.RunfastBusinessAccountsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author: lijin
 * @date: 2018年04月13日
 */

@Async
@Component("wmMessagePushTask")
@Slf4j
public class MessagePushTask {

    @Autowired
    private RunfastShopperService shopperService;

    @Autowired
    private RunfastCuserService cuserService;

    @Autowired
    private RunfastBusinessAccountsService businessAccountsService;

    @Autowired
    private RunfastLoginRecordService loginRecordService;

    @Autowired
    private AmqpClient amqpClient;

    @Autowired
    private RunfastAgentbusinessService agentbusinessService;


    /**
     * 商家接单
     * @param order
     */
    public void takenOrderNotity(RunfastGoodsSellRecord order) {
        amqpClient.publish(AmqpClient.WmBindingKey, order);


        String orderNo = order.getOrderCode();
        HashMap<String, String> params = new HashMap<>();
        params.put("orderNo", orderNo);
        String title = "外卖订单提醒";
        String alert = "你的订单"+orderNo+"商家已接单";
        String sound = null;


        /**
         * 推送通知给用户
         */
        Integer userId = order.getUserId();
        RunfastLoginRecordExample userLoginRecordExample = new RunfastLoginRecordExample();
        userLoginRecordExample.or().andAccountTypeEqualTo(0).andAccountIdEqualTo(userId).andLogoutTimeIsNull();
        List<RunfastLoginRecord> userLoginRecordList = loginRecordService.selectByExample(userLoginRecordExample);

        List<String> userAliasList = new ArrayList<>();
        for (RunfastLoginRecord loginRecord : userLoginRecordList) {

            String alias = loginRecord.getAlias();
            if(StringUtils.isNotBlank(alias)) userAliasList.add(alias);

        }
        if (!userAliasList.isEmpty()) {
            PushResult pushResult = JiGuangPushUtil.push(Role.Predefine.CUSTOMER, 600, userAliasList, alert,title, params, sound);
            if (!pushResult.isResultOK()) {

                StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
                log.error("文件名：" + stackTraceElement.getFileName()
                        + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                        + " 行号：" + stackTraceElement.getLineNumber()
                        + " 描述：" + pushResult.getOriginalContent());
            }
        }



    }

    public void newOrderNotify(RunfastGoodsSellRecord order) {
        amqpClient.publish(AmqpClient.WmBindingKey, order);


        String orderNo = order.getOrderCode();
        HashMap<String, String> params = new HashMap<>();
        params.put("orderNo", orderNo);
        String title = "外卖订单提醒";
        String alert = "您有新的外卖订单" + orderNo;
        String sound = "neworder.caf";

        /**
         * 推送通知给商家
         */
        RunfastBusinessAccountsExample businessAccountsExample = new RunfastBusinessAccountsExample();
        businessAccountsExample.or().andBusinessIdEqualTo(order.getBusinessId());
        List<RunfastBusinessAccounts> businessAccountsList = businessAccountsService.selectByExample(businessAccountsExample);
        List<String> businessAliasList = new ArrayList<>();
        for (RunfastBusinessAccounts businessAccounts : businessAccountsList) {

            RunfastLoginRecordExample loginRecordExample = new RunfastLoginRecordExample();
            loginRecordExample.or().andAccountTypeEqualTo(1).andAccountIdEqualTo(businessAccounts.getId()).andLogoutTimeIsNull();
            List<RunfastLoginRecord> loginRecordList = loginRecordService.selectByExample(loginRecordExample);


            for (RunfastLoginRecord loginRecord : loginRecordList) {

                String alias = loginRecord.getAlias();
                if(StringUtils.isNotBlank(alias)) businessAliasList.add(alias);
            }
        }

        if (!businessAliasList.isEmpty()) {
            PushResult pushResult = JiGuangPushUtil.push(Role.Predefine.BUSINESS, 600, businessAliasList, alert,title, params, sound);
            if (!pushResult.isResultOK()) {

                StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
                log.error("文件名：" + stackTraceElement.getFileName()
                        + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                        + " 行号：" + stackTraceElement.getLineNumber()
                        + " 描述：" + pushResult.getOriginalContent());
            }
        }



        /**
         * 推送通知给骑手
         */
        Integer isDeliver = order.getIsDeliver();
        Integer agentId = order.getAgentId();
        Boolean suportSelf = order.getSuportSelf();
        RunfastAgentbusiness agentbusiness = agentbusinessService.selectByPrimaryKey(agentId);
        Integer orderMode = agentbusiness.getOrder_mode();
        if(isDeliver!=null&&isDeliver==1&&orderMode!=2&&suportSelf!=null&&suportSelf){ //骑手接单模式：1抢单，2派送
            /**
             * 推送通知给骑手
             */
            RunfastShopperExample shopperExample = new RunfastShopperExample();
            shopperExample.createCriteria().andAgentIdEqualTo(agentId);
            List<RunfastShopper> shoppers = shopperService.selectByExample(shopperExample);


            List<String> driverAliasList = new ArrayList<>();
            for (RunfastShopper shopper : shoppers) {

                RunfastLoginRecordExample loginRecordExample = new RunfastLoginRecordExample();
                loginRecordExample.or().andAccountTypeEqualTo(2).andAccountIdEqualTo(shopper.getId()).andLogoutTimeIsNull();
                List<RunfastLoginRecord> loginRecordList = loginRecordService.selectByExample(loginRecordExample);


                for (RunfastLoginRecord loginRecord : loginRecordList) {

                    String alias = loginRecord.getAlias();
                    if(StringUtils.isNotBlank(alias)) driverAliasList.add(alias);
                }
            }
            if (!driverAliasList.isEmpty()) {
                PushResult pushResult = JiGuangPushUtil.push(Role.Predefine.DRIVER, 600, driverAliasList, alert,title, params, sound);
                if (!pushResult.isResultOK()) {

                    StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
                    log.error("文件名：" + stackTraceElement.getFileName()
                            + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                            + " 行号：" + stackTraceElement.getLineNumber()
                            + " 描述：" + pushResult.getOriginalContent());
                }
            }
        }

    }


    public void applyCancelOrderNotify(RunfastGoodsSellRecord order) {
        amqpClient.publish(AmqpClient.WmBindingKey, order);

        String orderNo = order.getOrderCode();
        HashMap<String, String> params = new HashMap<>();
        params.put("orderNo", orderNo);
        String title = "外卖订单提醒";
        String alert = "用户申请取消订单" + orderNo;
        String sound = null;

        /**
         * 推送通知给商家
         */
        RunfastBusinessAccountsExample businessAccountsExample = new RunfastBusinessAccountsExample();
        businessAccountsExample.or().andBusinessIdEqualTo(order.getBusinessId());
        List<RunfastBusinessAccounts> businessAccountsList = businessAccountsService.selectByExample(businessAccountsExample);
        List<String> businessAliasList = new ArrayList<>();
        for (RunfastBusinessAccounts businessAccounts : businessAccountsList) {

            RunfastLoginRecordExample loginRecordExample = new RunfastLoginRecordExample();
            loginRecordExample.or().andAccountTypeEqualTo(1).andAccountIdEqualTo(businessAccounts.getId()).andLogoutTimeIsNull();
            List<RunfastLoginRecord> loginRecordList = loginRecordService.selectByExample(loginRecordExample);


            for (RunfastLoginRecord loginRecord : loginRecordList) {

                String alias = loginRecord.getAlias();
                if(StringUtils.isNotBlank(alias)) businessAliasList.add(alias);
            }
        }

        if (!businessAliasList.isEmpty()) {
            PushResult pushResult = JiGuangPushUtil.push(Role.Predefine.BUSINESS, 600, businessAliasList, alert,title, params, sound);
            if (!pushResult.isResultOK()) {

                StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
                log.error("文件名：" + stackTraceElement.getFileName()
                        + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                        + " 行号：" + stackTraceElement.getLineNumber()
                        + " 描述：" + pushResult.getOriginalContent());
            }
        }


    }

    public void applyRefundNotify(RunfastGoodsSellRecord order) {
        amqpClient.publish(AmqpClient.WmBindingKey, order);

        String orderNo = order.getOrderCode();
        HashMap<String, String> params = new HashMap<>();
        params.put("orderNo", orderNo);
        String title = "外卖订单提醒";
        String alert = "用户申请退款" + orderNo;
        String sound = null;

        /**
         * 推送通知给商家
         */
        RunfastBusinessAccountsExample businessAccountsExample = new RunfastBusinessAccountsExample();
        businessAccountsExample.or().andBusinessIdEqualTo(order.getBusinessId());
        List<RunfastBusinessAccounts> businessAccountsList = businessAccountsService.selectByExample(businessAccountsExample);
        List<String> businessAliasList = new ArrayList<>();
        for (RunfastBusinessAccounts businessAccounts : businessAccountsList) {

            RunfastLoginRecordExample loginRecordExample = new RunfastLoginRecordExample();
            loginRecordExample.or().andAccountTypeEqualTo(1).andAccountIdEqualTo(businessAccounts.getId()).andLogoutTimeIsNull();
            List<RunfastLoginRecord> loginRecordList = loginRecordService.selectByExample(loginRecordExample);


            for (RunfastLoginRecord loginRecord : loginRecordList) {

                String alias = loginRecord.getAlias();
                if(StringUtils.isNotBlank(alias)) businessAliasList.add(alias);
            }
        }

        if (!businessAliasList.isEmpty()) {
            PushResult pushResult = JiGuangPushUtil.push(Role.Predefine.BUSINESS, 600, businessAliasList, alert,title, params, sound);
            if (!pushResult.isResultOK()) {

                StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
                log.error("文件名：" + stackTraceElement.getFileName()
                        + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                        + " 行号：" + stackTraceElement.getLineNumber()
                        + " 描述：" + pushResult.getOriginalContent());
            }
        }


    }
}
